<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">后台管理系统</div>
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="loginForm.userName" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" type="password"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="loginForm.code" style="width: 180px;"></el-input>
          <div class="verify-code" @click="refreshCode">
            {{ verifyCode }}
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/user'

export default {
  data() {
    return {
      loginForm: {
        userName: '',
        password: '',
        code: ''
      },
      loginRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
        ]
      },
      verifyCode: this.generateCode(),
      loading: false
    }
  },
  methods: {
    generateCode() {
      let code = '';
      const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      for (let i = 0; i < 4; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return code;
    },
    refreshCode() {
      this.verifyCode = this.generateCode();
    },
    async handleLogin() {
      this.$refs.loginFormRef.validate(async valid => {
        if (valid) {
          if (this.loginForm.code !== this.verifyCode) {
            this.$message.error('验证码错误');
            this.refreshCode();
            return;
          }
          
          this.loading = true;
          try {
            const response = await login({
              userName: this.loginForm.userName,
              password: this.loginForm.password
            });
            
            // 检查响应是否成功
            if (response.success) {
              // 存储token和用户信息
              localStorage.setItem('token', response.data.token);
              localStorage.setItem('user', JSON.stringify(response.data.user));
              localStorage.setItem('roles', JSON.stringify(response.data.roles));
              localStorage.setItem('expireTime', response.data.expireTime);
              
              this.$message({
                type: 'success',
                message: response.message || '登录成功'
              });
              
              // 跳转到首页
              this.$router.push('/');
            } else {
              this.$message.error(response.message || '登录失败');
              this.refreshCode();
            }
          } catch (error) {
            this.$message.error(error.message || '登录失败，请检查网络连接');
            this.refreshCode();
          } finally {
            this.loading = false;
          }
        }
      });
    },
    resetForm() {
      this.$refs.loginFormRef.resetFields();
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 30px;
  color: #333;
}

.verify-code {
  display: inline-block;
  width: 100px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: #f0f0f0;
  margin-left: 10px;
  vertical-align: middle;
  cursor: pointer;
  font-family: monospace;
  font-size: 16px;
  letter-spacing: 2px;
}
</style>